import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import SupplierView from '../views/SupplierView.vue'
import SheepInventoryView from '../views/SheepInventoryView.vue'
import MapTestView from '../views/MapTestView.vue'
import SimpleMapTest from '../views/SimpleMapTest.vue'
import BaiduMapTest from '../views/BaiduMapTest.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'  // 默认重定向到登录页
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }
    },
    {
      path: '/supplier',
      name: 'supplier',
      component: SupplierView,
      meta: { requiresAuth: true }
    },
    {
      path: '/sheep-inventory',
      name: 'sheep-inventory',
      component: SheepInventoryView,
      meta: { requiresAuth: true }
    },
    {
      path: '/map-test',
      name: 'map-test',
      component: MapTestView,
      meta: { requiresAuth: true }
    },
            {
          path: '/simple-map-test',
          name: 'simple-map-test',
          component: SimpleMapTest,
          meta: { requiresAuth: true }
        },
        {
          path: '/baidu-map-test',
          name: 'baidu-map-test',
          component: BaiduMapTest,
          meta: { requiresAuth: true }
        },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !token) {
    // 需要认证但未登录，跳转到登录页
    next('/login')
  } else if (to.path === '/login' && token) {
    // 已登录但访问登录页，跳转到首页
    next('/home')
  } else {
    next()
  }
})

export default router
